/*
 * @Description: 
 * @Author: Wen
 * @Date: 2024-11-19 11:33:07
 * @LastEditors: Wen
 * @LastEditTime: 2024-11-19 15:57:57
 * 太棒了，又坚持了一天
 */

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.Test;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Properties;
import java.util.ArrayList;


public class DruidTest {
  @Test
  public void test() {
    Connection conn = null;
    // 声明操作对象
    // 1.Statement-容易被sql注入
    // 2.PreparedStatement-防止sql注入
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    // 1. 加载配置文件
    Properties properties = new Properties();
    InputStream iStream = DruidTest.class.getClassLoader().getResourceAsStream("druid.properties");
    try {
      properties.load(iStream);
      // properties.forEach((k, v) -> System.out.println(k + ":" + v));
      // 2. 获取连接池对象
      DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
      conn = dataSource.getConnection();
      System.out.println("conn: " + conn);
      // 3.获取操作对象
      // 3.1准备sql语句-查询id为2的user
      // String sql = "select * from t_user where id = ?";
      String sql ="select * from t_user";
      pstmt =conn.prepareStatement(sql);
      // 设置sql语句中的第一个参数，值为2
      // pstmt.setInt(1,2);
      // 4.执行查询语句
      rs = pstmt.executeQuery();
      List<User> list =new ArrayList<>();
      while(rs.next()){
        // 获取返回值
        int id =rs.getInt(1);
        String name = rs.getString(2);
        // String name = rs.getString("name");
        String password = rs.getString("password");
        int age = rs.getInt("age");
        // System.out.println("id="+id+",name="+name+",password="+password+",age="+age);
        // 将查询结果转为 对象
        User u = new User(id,name,password,age);
        System.out.println(u);
        // 查询结果放到一个list中 输出list
        list.add(u);
        System.out.println(list); 
        
      }

    } catch (Exception e) {
      // TODO: handle exception
      e.printStackTrace();
    }
  }

}